
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Database transactions &#8212; Django 3.2.6.dev 文档</title>
    <link rel="stylesheet" href="../../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../../" src="../../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../../_static/jquery.js"></script>
    <script type="text/javascript" src="../../_static/underscore.js"></script>
    <script type="text/javascript" src="../../_static/doctools.js"></script>
    <script type="text/javascript" src="../../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../../genindex.html" />
    <link rel="search" title="搜索" href="../../search.html" />
    <link rel="next" title="Multiple databases" href="multi-db.html" />
    <link rel="prev" title="Performing raw SQL queries" href="sql.html" />



 
<script src="../../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);</script>

  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../../index.html">Django 3.2.6.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../../index.html">Home</a>  |
        <a title="Table of contents" href="../../contents.html">Table of contents</a>  |
        <a title="Global index" href="../../genindex.html">Index</a>  |
        <a title="Module index" href="../../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="sql.html" title="Performing raw SQL queries">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="multi-db.html" title="Multiple databases">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="topics-db-transactions">
            
  <div class="section" id="s-module-django.db.transaction">
<span id="s-database-transactions"></span><span id="module-django.db.transaction"></span><span id="database-transactions"></span><h1>Database transactions<a class="headerlink" href="#module-django.db.transaction" title="永久链接至标题">¶</a></h1>
<p>Django gives you a few ways to control how database transactions are managed.</p>
<div class="section" id="s-managing-database-transactions">
<span id="managing-database-transactions"></span><h2>Managing database transactions<a class="headerlink" href="#managing-database-transactions" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-django-s-default-transaction-behavior">
<span id="django-s-default-transaction-behavior"></span><h3>Django's default transaction behavior<a class="headerlink" href="#django-s-default-transaction-behavior" title="永久链接至标题">¶</a></h3>
<p>Django's default behavior is to run in autocommit mode. Each query is
immediately committed to the database, unless a transaction is active.
<a class="reference internal" href="#autocommit-details"><span class="std std-ref">See below for details</span></a>.</p>
<p>Django uses transactions or savepoints automatically to guarantee the
integrity of ORM operations that require multiple queries, especially
<a class="reference internal" href="queries.html#topics-db-queries-delete"><span class="std std-ref">delete()</span></a> and <a class="reference internal" href="queries.html#topics-db-queries-update"><span class="std std-ref">update()</span></a> queries.</p>
<p>Django's <a class="reference internal" href="../testing/tools.html#django.test.TestCase" title="django.test.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> class also wraps each test in a
transaction for performance reasons.</p>
</div>
<div class="section" id="s-tying-transactions-to-http-requests">
<span id="s-id1"></span><span id="tying-transactions-to-http-requests"></span><span id="id1"></span><h3>Tying transactions to HTTP requests<a class="headerlink" href="#tying-transactions-to-http-requests" title="永久链接至标题">¶</a></h3>
<p>A common way to handle transactions on the web is to wrap each request in a
transaction. Set <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-ATOMIC_REQUESTS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">ATOMIC_REQUESTS</span></code></a> to
<code class="docutils literal notranslate"><span class="pre">True</span></code> in the configuration of each database for which you want to enable
this behavior.</p>
<p>It works like this. Before calling a view function, Django starts a
transaction. If the response is produced without problems, Django commits the
transaction. If the view produces an exception, Django rolls back the
transaction.</p>
<p>You may perform subtransactions using savepoints in your view code, typically
with the <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> context manager. However, at the end of the view,
either all or none of the changes will be committed.</p>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p class="last">While the simplicity of this transaction model is appealing, it also makes it
inefficient when traffic increases. Opening a transaction for every view has
some overhead. The impact on performance depends on the query patterns of your
application and on how well your database handles locking.</p>
</div>
<div class="admonition-per-request-transactions-and-streaming-responses admonition">
<p class="first admonition-title">Per-request transactions and streaming responses</p>
<p>When a view returns a <a class="reference internal" href="../../ref/request-response.html#django.http.StreamingHttpResponse" title="django.http.StreamingHttpResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">StreamingHttpResponse</span></code></a>, reading
the contents of the response will often execute code to generate the
content. Since the view has already returned, such code runs outside of
the transaction.</p>
<p class="last">Generally speaking, it isn't advisable to write to the database while
generating a streaming response, since there's no sensible way to handle
errors after starting to send the response.</p>
</div>
<p>In practice, this feature wraps every view function in the <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a>
decorator described below.</p>
<p>Note that only the execution of your view is enclosed in the transactions.
Middleware runs outside of the transaction, and so does the rendering of
template responses.</p>
<p>When <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-ATOMIC_REQUESTS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">ATOMIC_REQUESTS</span></code></a> is enabled, it's
still possible to prevent views from running in a transaction.</p>
<dl class="function">
<dt id="django.db.transaction.non_atomic_requests">
<code class="descname">non_atomic_requests</code>(<em>using=None</em>)<a class="headerlink" href="#django.db.transaction.non_atomic_requests" title="永久链接至目标">¶</a></dt>
<dd><p>This decorator will negate the effect of <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-ATOMIC_REQUESTS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">ATOMIC_REQUESTS</span></code></a> for a given view:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">transaction</span>

<span class="nd">@transaction</span><span class="o">.</span><span class="n">non_atomic_requests</span>
<span class="k">def</span> <span class="nf">my_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">do_stuff</span><span class="p">()</span>

<span class="nd">@transaction</span><span class="o">.</span><span class="n">non_atomic_requests</span><span class="p">(</span><span class="n">using</span><span class="o">=</span><span class="s1">&#39;other&#39;</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">my_other_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">do_stuff_on_the_other_database</span><span class="p">()</span>
</pre></div>
</div>
<p>It only works if it's applied to the view itself.</p>
</dd></dl>

</div>
<div class="section" id="s-controlling-transactions-explicitly">
<span id="controlling-transactions-explicitly"></span><h3>Controlling transactions explicitly<a class="headerlink" href="#controlling-transactions-explicitly" title="永久链接至标题">¶</a></h3>
<p>Django provides a single API to control database transactions.</p>
<dl class="function">
<dt id="django.db.transaction.atomic">
<code class="descname">atomic</code>(<em>using=None</em>, <em>savepoint=True</em>, <em>durable=False</em>)<a class="headerlink" href="#django.db.transaction.atomic" title="永久链接至目标">¶</a></dt>
<dd><p>Atomicity is the defining property of database transactions. <code class="docutils literal notranslate"><span class="pre">atomic</span></code>
allows us to create a block of code within which the atomicity on the
database is guaranteed. If the block of code is successfully completed, the
changes are committed to the database. If there is an exception, the
changes are rolled back.</p>
<p><code class="docutils literal notranslate"><span class="pre">atomic</span></code> blocks can be nested. In this case, when an inner block
completes successfully, its effects can still be rolled back if an
exception is raised in the outer block at a later point.</p>
<p>It is sometimes useful to ensure an <code class="docutils literal notranslate"><span class="pre">atomic</span></code> block is always the
outermost <code class="docutils literal notranslate"><span class="pre">atomic</span></code> block, ensuring that any database changes are
committed when the block is exited without errors. This is known as
durability and can be achieved by setting <code class="docutils literal notranslate"><span class="pre">durable=True</span></code>. If the
<code class="docutils literal notranslate"><span class="pre">atomic</span></code> block is nested within another it raises a <code class="docutils literal notranslate"><span class="pre">RuntimeError</span></code>.</p>
<p><code class="docutils literal notranslate"><span class="pre">atomic</span></code> is usable both as a <a class="reference external" href="https://docs.python.org/3/glossary.html#term-decorator" title="(在 Python v3.9)"><span class="xref std std-term">decorator</span></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">transaction</span>

<span class="nd">@transaction</span><span class="o">.</span><span class="n">atomic</span>
<span class="k">def</span> <span class="nf">viewfunc</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c1"># This code executes inside a transaction.</span>
    <span class="n">do_stuff</span><span class="p">()</span>
</pre></div>
</div>
<p>and as a <a class="reference external" href="https://docs.python.org/3/glossary.html#term-context-manager" title="(在 Python v3.9)"><span class="xref std std-term">context manager</span></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">transaction</span>

<span class="k">def</span> <span class="nf">viewfunc</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c1"># This code executes in autocommit mode (Django&#39;s default).</span>
    <span class="n">do_stuff</span><span class="p">()</span>

    <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">():</span>
        <span class="c1"># This code executes inside a transaction.</span>
        <span class="n">do_more_stuff</span><span class="p">()</span>
</pre></div>
</div>
<p>Wrapping <code class="docutils literal notranslate"><span class="pre">atomic</span></code> in a try/except block allows for natural handling of
integrity errors:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">IntegrityError</span><span class="p">,</span> <span class="n">transaction</span>

<span class="nd">@transaction</span><span class="o">.</span><span class="n">atomic</span>
<span class="k">def</span> <span class="nf">viewfunc</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="n">create_parent</span><span class="p">()</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">():</span>
            <span class="n">generate_relationships</span><span class="p">()</span>
    <span class="k">except</span> <span class="n">IntegrityError</span><span class="p">:</span>
        <span class="n">handle_exception</span><span class="p">()</span>

    <span class="n">add_children</span><span class="p">()</span>
</pre></div>
</div>
<p>In this example, even if <code class="docutils literal notranslate"><span class="pre">generate_relationships()</span></code> causes a database
error by breaking an integrity constraint, you can execute queries in
<code class="docutils literal notranslate"><span class="pre">add_children()</span></code>, and the changes from <code class="docutils literal notranslate"><span class="pre">create_parent()</span></code> are still
there and bound to the same transaction. Note that any operations attempted
in <code class="docutils literal notranslate"><span class="pre">generate_relationships()</span></code> will already have been rolled back safely
when <code class="docutils literal notranslate"><span class="pre">handle_exception()</span></code> is called, so the exception handler can also
operate on the database if necessary.</p>
<div class="admonition-avoid-catching-exceptions-inside-atomic admonition">
<p class="first admonition-title">Avoid catching exceptions inside <code class="docutils literal notranslate"><span class="pre">atomic</span></code>!</p>
<p>When exiting an <code class="docutils literal notranslate"><span class="pre">atomic</span></code> block, Django looks at whether it's exited
normally or with an exception to determine whether to commit or roll
back. If you catch and handle exceptions inside an <code class="docutils literal notranslate"><span class="pre">atomic</span></code> block,
you may hide from Django the fact that a problem has happened. This
can result in unexpected behavior.</p>
<p>This is mostly a concern for <a class="reference internal" href="../../ref/exceptions.html#django.db.DatabaseError" title="django.db.DatabaseError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">DatabaseError</span></code></a> and its
subclasses such as <a class="reference internal" href="../../ref/exceptions.html#django.db.IntegrityError" title="django.db.IntegrityError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">IntegrityError</span></code></a>. After such an
error, the transaction is broken and Django will perform a rollback at
the end of the <code class="docutils literal notranslate"><span class="pre">atomic</span></code> block. If you attempt to run database
queries before the rollback happens, Django will raise a
<a class="reference internal" href="../../ref/exceptions.html#django.db.transaction.TransactionManagementError" title="django.db.transaction.TransactionManagementError"><code class="xref py py-class docutils literal notranslate"><span class="pre">TransactionManagementError</span></code></a>. You may
also encounter this behavior when an ORM-related signal handler raises
an exception.</p>
<p>The correct way to catch database errors is around an <code class="docutils literal notranslate"><span class="pre">atomic</span></code> block
as shown above. If necessary, add an extra <code class="docutils literal notranslate"><span class="pre">atomic</span></code> block for this
purpose. This pattern has another advantage: it delimits explicitly
which operations will be rolled back if an exception occurs.</p>
<p class="last">If you catch exceptions raised by raw SQL queries, Django's behavior
is unspecified and database-dependent.</p>
</div>
<div class="admonition-you-may-need-to-manually-revert-model-state-when-rolling-back-a-transaction admonition">
<p class="first admonition-title">You may need to manually revert model state when rolling back a transaction.</p>
<p>The values of a model's fields won't be reverted when a transaction
rollback happens. This could lead to an inconsistent model state unless
you manually restore the original field values.</p>
<p>For example, given <code class="docutils literal notranslate"><span class="pre">MyModel</span></code> with an <code class="docutils literal notranslate"><span class="pre">active</span></code> field, this snippet
ensures that the <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">obj.active</span></code> check at the end uses the correct
value if updating <code class="docutils literal notranslate"><span class="pre">active</span></code> to <code class="docutils literal notranslate"><span class="pre">True</span></code> fails in the transaction:</p>
<div class="last highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">DatabaseError</span><span class="p">,</span> <span class="n">transaction</span>

<span class="n">obj</span> <span class="o">=</span> <span class="n">MyModel</span><span class="p">(</span><span class="n">active</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>
<span class="n">obj</span><span class="o">.</span><span class="n">active</span> <span class="o">=</span> <span class="kc">True</span>
<span class="k">try</span><span class="p">:</span>
    <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">():</span>
        <span class="n">obj</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
<span class="k">except</span> <span class="n">DatabaseError</span><span class="p">:</span>
    <span class="n">obj</span><span class="o">.</span><span class="n">active</span> <span class="o">=</span> <span class="kc">False</span>

<span class="k">if</span> <span class="n">obj</span><span class="o">.</span><span class="n">active</span><span class="p">:</span>
    <span class="o">...</span>
</pre></div>
</div>
</div>
<p>In order to guarantee atomicity, <code class="docutils literal notranslate"><span class="pre">atomic</span></code> disables some APIs. Attempting
to commit, roll back, or change the autocommit state of the database
connection within an <code class="docutils literal notranslate"><span class="pre">atomic</span></code> block will raise an exception.</p>
<p><code class="docutils literal notranslate"><span class="pre">atomic</span></code> takes a <code class="docutils literal notranslate"><span class="pre">using</span></code> argument which should be the name of a
database. If this argument isn't provided, Django uses the <code class="docutils literal notranslate"><span class="pre">&quot;default&quot;</span></code>
database.</p>
<p>Under the hood, Django's transaction management code:</p>
<ul class="simple">
<li>opens a transaction when entering the outermost <code class="docutils literal notranslate"><span class="pre">atomic</span></code> block;</li>
<li>creates a savepoint when entering an inner <code class="docutils literal notranslate"><span class="pre">atomic</span></code> block;</li>
<li>releases or rolls back to the savepoint when exiting an inner block;</li>
<li>commits or rolls back the transaction when exiting the outermost block.</li>
</ul>
<p>You can disable the creation of savepoints for inner blocks by setting the
<code class="docutils literal notranslate"><span class="pre">savepoint</span></code> argument to <code class="docutils literal notranslate"><span class="pre">False</span></code>. If an exception occurs, Django will
perform the rollback when exiting the first parent block with a savepoint
if there is one, and the outermost block otherwise. Atomicity is still
guaranteed by the outer transaction. This option should only be used if
the overhead of savepoints is noticeable. It has the drawback of breaking
the error handling described above.</p>
<p>You may use <code class="docutils literal notranslate"><span class="pre">atomic</span></code> when autocommit is turned off. It will only use
savepoints, even for the outermost block.</p>
</dd></dl>

<div class="admonition-performance-considerations admonition">
<p class="first admonition-title">Performance considerations</p>
<p class="last">Open transactions have a performance cost for your database server. To
minimize this overhead, keep your transactions as short as possible. This
is especially important if you're using <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> in long-running
processes, outside of Django's request / response cycle.</p>
</div>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p class="last"><a class="reference internal" href="../testing/tools.html#django.test.TestCase" title="django.test.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.test.TestCase</span></code></a> disables the durability check to allow
testing durable atomic blocks in a transaction for performance reasons. Use
<a class="reference internal" href="../testing/tools.html#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">django.test.TransactionTestCase</span></code></a> for testing durability.</p>
</div>
<div class="versionchanged">
<span class="title">Changed in Django 3.2:</span> <p>The <code class="docutils literal notranslate"><span class="pre">durable</span></code> argument was added.</p>
</div>
</div>
</div>
<div class="section" id="s-autocommit">
<span id="autocommit"></span><h2>Autocommit<a class="headerlink" href="#autocommit" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-why-django-uses-autocommit">
<span id="s-autocommit-details"></span><span id="why-django-uses-autocommit"></span><span id="autocommit-details"></span><h3>Why Django uses autocommit<a class="headerlink" href="#why-django-uses-autocommit" title="永久链接至标题">¶</a></h3>
<p>In the SQL standards, each SQL query starts a transaction, unless one is
already active. Such transactions must then be explicitly committed or rolled
back.</p>
<p>This isn't always convenient for application developers. To alleviate this
problem, most databases provide an autocommit mode. When autocommit is turned
on and no transaction is active, each SQL query gets wrapped in its own
transaction. In other words, not only does each such query start a
transaction, but the transaction also gets automatically committed or rolled
back, depending on whether the query succeeded.</p>
<p><span class="target" id="index-0"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a>, the Python Database API Specification v2.0, requires autocommit to
be initially turned off. Django overrides this default and turns autocommit
on.</p>
<p>To avoid this, you can <a class="reference internal" href="#deactivate-transaction-management"><span class="std std-ref">deactivate the transaction management</span></a>, but it isn't recommended.</p>
</div>
<div class="section" id="s-deactivating-transaction-management">
<span id="s-deactivate-transaction-management"></span><span id="deactivating-transaction-management"></span><span id="deactivate-transaction-management"></span><h3>Deactivating transaction management<a class="headerlink" href="#deactivating-transaction-management" title="永久链接至标题">¶</a></h3>
<p>You can totally disable Django's transaction management for a given database
by setting <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-AUTOCOMMIT"><code class="xref std std-setting docutils literal notranslate"><span class="pre">AUTOCOMMIT</span></code></a> to <code class="docutils literal notranslate"><span class="pre">False</span></code> in its
configuration. If you do this, Django won't enable autocommit, and won't
perform any commits. You'll get the regular behavior of the underlying
database library.</p>
<p>This requires you to commit explicitly every transaction, even those started
by Django or by third-party libraries. Thus, this is best used in situations
where you want to run your own transaction-controlling middleware or do
something really strange.</p>
</div>
</div>
<div class="section" id="s-performing-actions-after-commit">
<span id="performing-actions-after-commit"></span><h2>Performing actions after commit<a class="headerlink" href="#performing-actions-after-commit" title="永久链接至标题">¶</a></h2>
<p>Sometimes you need to perform an action related to the current database
transaction, but only if the transaction successfully commits. Examples might
include a <a class="reference external" href="https://pypi.org/project/celery/">Celery</a> task, an email notification, or a cache invalidation.</p>
<p>Django provides the <a class="reference internal" href="#django.db.transaction.on_commit" title="django.db.transaction.on_commit"><code class="xref py py-func docutils literal notranslate"><span class="pre">on_commit()</span></code></a> function to register callback functions
that should be executed after a transaction is successfully committed:</p>
<dl class="function">
<dt id="django.db.transaction.on_commit">
<code class="descname">on_commit</code>(<em>func</em>, <em>using=None</em>)<a class="headerlink" href="#django.db.transaction.on_commit" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>Pass any function (that takes no arguments) to <a class="reference internal" href="#django.db.transaction.on_commit" title="django.db.transaction.on_commit"><code class="xref py py-func docutils literal notranslate"><span class="pre">on_commit()</span></code></a>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">transaction</span>

<span class="k">def</span> <span class="nf">do_something</span><span class="p">():</span>
    <span class="k">pass</span>  <span class="c1"># send a mail, invalidate a cache, fire off a Celery task, etc.</span>

<span class="n">transaction</span><span class="o">.</span><span class="n">on_commit</span><span class="p">(</span><span class="n">do_something</span><span class="p">)</span>
</pre></div>
</div>
<p>You can also wrap your function in a lambda:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">transaction</span><span class="o">.</span><span class="n">on_commit</span><span class="p">(</span><span class="k">lambda</span><span class="p">:</span> <span class="n">some_celery_task</span><span class="o">.</span><span class="n">delay</span><span class="p">(</span><span class="s1">&#39;arg1&#39;</span><span class="p">))</span>
</pre></div>
</div>
<p>The function you pass in will be called immediately after a hypothetical
database write made where <code class="docutils literal notranslate"><span class="pre">on_commit()</span></code> is called would be successfully
committed.</p>
<p>If you call <code class="docutils literal notranslate"><span class="pre">on_commit()</span></code> while there isn't an active transaction, the
callback will be executed immediately.</p>
<p>If that hypothetical database write is instead rolled back (typically when an
unhandled exception is raised in an <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> block), your function will
be discarded and never called.</p>
<div class="section" id="s-savepoints">
<span id="savepoints"></span><h3>Savepoints<a class="headerlink" href="#savepoints" title="永久链接至标题">¶</a></h3>
<p>Savepoints (i.e. nested <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> blocks) are handled correctly. That is,
an <a class="reference internal" href="#django.db.transaction.on_commit" title="django.db.transaction.on_commit"><code class="xref py py-func docutils literal notranslate"><span class="pre">on_commit()</span></code></a> callable registered after a savepoint (in a nested
<a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> block) will be called after the outer transaction is committed,
but not if a rollback to that savepoint or any previous savepoint occurred
during the transaction:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">():</span>  <span class="c1"># Outer atomic, start a new transaction</span>
    <span class="n">transaction</span><span class="o">.</span><span class="n">on_commit</span><span class="p">(</span><span class="n">foo</span><span class="p">)</span>

    <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">():</span>  <span class="c1"># Inner atomic block, create a savepoint</span>
        <span class="n">transaction</span><span class="o">.</span><span class="n">on_commit</span><span class="p">(</span><span class="n">bar</span><span class="p">)</span>

<span class="c1"># foo() and then bar() will be called when leaving the outermost block</span>
</pre></div>
</div>
<p>On the other hand, when a savepoint is rolled back (due to an exception being
raised), the inner callable will not be called:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">():</span>  <span class="c1"># Outer atomic, start a new transaction</span>
    <span class="n">transaction</span><span class="o">.</span><span class="n">on_commit</span><span class="p">(</span><span class="n">foo</span><span class="p">)</span>

    <span class="k">try</span><span class="p">:</span>
        <span class="k">with</span> <span class="n">transaction</span><span class="o">.</span><span class="n">atomic</span><span class="p">():</span>  <span class="c1"># Inner atomic block, create a savepoint</span>
            <span class="n">transaction</span><span class="o">.</span><span class="n">on_commit</span><span class="p">(</span><span class="n">bar</span><span class="p">)</span>
            <span class="k">raise</span> <span class="n">SomeError</span><span class="p">()</span>  <span class="c1"># Raising an exception - abort the savepoint</span>
    <span class="k">except</span> <span class="n">SomeError</span><span class="p">:</span>
        <span class="k">pass</span>

<span class="c1"># foo() will be called, but not bar()</span>
</pre></div>
</div>
</div>
<div class="section" id="s-order-of-execution">
<span id="order-of-execution"></span><h3>Order of execution<a class="headerlink" href="#order-of-execution" title="永久链接至标题">¶</a></h3>
<p>On-commit functions for a given transaction are executed in the order they were
registered.</p>
</div>
<div class="section" id="s-exception-handling">
<span id="exception-handling"></span><h3>Exception handling<a class="headerlink" href="#exception-handling" title="永久链接至标题">¶</a></h3>
<p>If one on-commit function within a given transaction raises an uncaught
exception, no later registered functions in that same transaction will run.
This is the same behavior as if you'd executed the functions sequentially
yourself without <a class="reference internal" href="#django.db.transaction.on_commit" title="django.db.transaction.on_commit"><code class="xref py py-func docutils literal notranslate"><span class="pre">on_commit()</span></code></a>.</p>
</div>
<div class="section" id="s-timing-of-execution">
<span id="timing-of-execution"></span><h3>Timing of execution<a class="headerlink" href="#timing-of-execution" title="永久链接至标题">¶</a></h3>
<p>Your callbacks are executed <em>after</em> a successful commit, so a failure in a
callback will not cause the transaction to roll back. They are executed
conditionally upon the success of the transaction, but they are not <em>part</em> of
the transaction. For the intended use cases (mail notifications, Celery tasks,
etc.), this should be fine. If it's not (if your follow-up action is so
critical that its failure should mean the failure of the transaction itself),
then you don't want to use the <a class="reference internal" href="#django.db.transaction.on_commit" title="django.db.transaction.on_commit"><code class="xref py py-func docutils literal notranslate"><span class="pre">on_commit()</span></code></a> hook. Instead, you may want
<a class="reference external" href="https://en.wikipedia.org/wiki/Two-phase_commit_protocol">two-phase commit</a> such as the <a class="reference external" href="https://www.psycopg.org/docs/usage.html#tpc" title="(在 Psycopg v2.9)"><span class="xref std std-ref">psycopg Two-Phase Commit protocol support</span></a> and the <span class="target" id="index-1"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0249#optional-two-phase-commit-extensions"><strong>optional Two-Phase Commit Extensions in the
Python DB-API specification</strong></a>.</p>
<p>Callbacks are not run until autocommit is restored on the connection following
the commit (because otherwise any queries done in a callback would open an
implicit transaction, preventing the connection from going back into autocommit
mode).</p>
<p>When in autocommit mode and outside of an <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> block, the function
will run immediately, not on commit.</p>
<p>On-commit functions only work with <a class="reference internal" href="#managing-autocommit"><span class="std std-ref">autocommit mode</span></a>
and the <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> (or <a class="reference internal" href="../../ref/settings.html#std:setting-DATABASE-ATOMIC_REQUESTS"><code class="xref std std-setting docutils literal notranslate"><span class="pre">ATOMIC_REQUESTS</span></code></a>) transaction API. Calling <a class="reference internal" href="#django.db.transaction.on_commit" title="django.db.transaction.on_commit"><code class="xref py py-func docutils literal notranslate"><span class="pre">on_commit()</span></code></a> when
autocommit is disabled and you are not within an atomic block will result in an
error.</p>
</div>
<div class="section" id="s-use-in-tests">
<span id="use-in-tests"></span><h3>Use in tests<a class="headerlink" href="#use-in-tests" title="永久链接至标题">¶</a></h3>
<p>Django's <a class="reference internal" href="../testing/tools.html#django.test.TestCase" title="django.test.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a> class wraps each test in a transaction
and rolls back that transaction after each test, in order to provide test
isolation. This means that no transaction is ever actually committed, thus your
<a class="reference internal" href="#django.db.transaction.on_commit" title="django.db.transaction.on_commit"><code class="xref py py-func docutils literal notranslate"><span class="pre">on_commit()</span></code></a> callbacks will never be run.</p>
<p>You can overcome this limitation by using
<a class="reference internal" href="../testing/tools.html#django.test.TestCase.captureOnCommitCallbacks" title="django.test.TestCase.captureOnCommitCallbacks"><code class="xref py py-meth docutils literal notranslate"><span class="pre">TestCase.captureOnCommitCallbacks()</span></code></a>. This captures your
<a class="reference internal" href="#django.db.transaction.on_commit" title="django.db.transaction.on_commit"><code class="xref py py-func docutils literal notranslate"><span class="pre">on_commit()</span></code></a> callbacks in a list, allowing you to make assertions on them,
or emulate the transaction committing by calling them.</p>
<p>Another way to overcome the limitation is to use
<a class="reference internal" href="../testing/tools.html#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TransactionTestCase</span></code></a> instead of
<a class="reference internal" href="../testing/tools.html#django.test.TestCase" title="django.test.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>. This will mean your transactions are committed,
and the callbacks will run. However
<a class="reference internal" href="../testing/tools.html#django.test.TransactionTestCase" title="django.test.TransactionTestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TransactionTestCase</span></code></a> flushes the database between tests,
which is significantly slower than <a class="reference internal" href="../testing/tools.html#django.test.TestCase" title="django.test.TestCase"><code class="xref py py-class docutils literal notranslate"><span class="pre">TestCase</span></code></a>'s isolation.</p>
</div>
<div class="section" id="s-why-no-rollback-hook">
<span id="why-no-rollback-hook"></span><h3>Why no rollback hook?<a class="headerlink" href="#why-no-rollback-hook" title="永久链接至标题">¶</a></h3>
<p>A rollback hook is harder to implement robustly than a commit hook, since a
variety of things can cause an implicit rollback.</p>
<p>For instance, if your database connection is dropped because your process was
killed without a chance to shut down gracefully, your rollback hook will never
run.</p>
<p>But there is a solution: instead of doing something during the atomic block
(transaction) and then undoing it if the transaction fails, use
<a class="reference internal" href="#django.db.transaction.on_commit" title="django.db.transaction.on_commit"><code class="xref py py-func docutils literal notranslate"><span class="pre">on_commit()</span></code></a> to delay doing it in the first place until after the
transaction succeeds. It's a lot easier to undo something you never did in the
first place!</p>
</div>
</div>
<div class="section" id="s-low-level-apis">
<span id="low-level-apis"></span><h2>Low-level APIs<a class="headerlink" href="#low-level-apis" title="永久链接至标题">¶</a></h2>
<div class="admonition warning">
<p class="first admonition-title">警告</p>
<p>Always prefer <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> if possible at all. It accounts for the
idiosyncrasies of each database and prevents invalid operations.</p>
<p class="last">The low level APIs are only useful if you're implementing your own
transaction management.</p>
</div>
<div class="section" id="s-managing-autocommit">
<span id="s-id2"></span><span id="managing-autocommit"></span><span id="id2"></span><h3>Autocommit<a class="headerlink" href="#managing-autocommit" title="永久链接至标题">¶</a></h3>
<p>Django provides an API in the <a class="reference internal" href="#module-django.db.transaction" title="django.db.transaction"><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.db.transaction</span></code></a> module to manage the
autocommit state of each database connection.</p>
<dl class="function">
<dt id="django.db.transaction.get_autocommit">
<code class="descname">get_autocommit</code>(<em>using=None</em>)<a class="headerlink" href="#django.db.transaction.get_autocommit" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="django.db.transaction.set_autocommit">
<code class="descname">set_autocommit</code>(<em>autocommit</em>, <em>using=None</em>)<a class="headerlink" href="#django.db.transaction.set_autocommit" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>These functions take a <code class="docutils literal notranslate"><span class="pre">using</span></code> argument which should be the name of a
database. If it isn't provided, Django uses the <code class="docutils literal notranslate"><span class="pre">&quot;default&quot;</span></code> database.</p>
<p>Autocommit is initially turned on. If you turn it off, it's your
responsibility to restore it.</p>
<p>Once you turn autocommit off, you get the default behavior of your database
adapter, and Django won't help you. Although that behavior is specified in
<span class="target" id="index-2"></span><a class="pep reference external" href="https://www.python.org/dev/peps/pep-0249"><strong>PEP 249</strong></a>, implementations of adapters aren't always consistent with one
another. Review the documentation of the adapter you're using carefully.</p>
<p>You must ensure that no transaction is active, usually by issuing a
<a class="reference internal" href="#django.db.transaction.commit" title="django.db.transaction.commit"><code class="xref py py-func docutils literal notranslate"><span class="pre">commit()</span></code></a> or a <a class="reference internal" href="#django.db.transaction.rollback" title="django.db.transaction.rollback"><code class="xref py py-func docutils literal notranslate"><span class="pre">rollback()</span></code></a>, before turning autocommit back on.</p>
<p>Django will refuse to turn autocommit off when an <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> block is
active, because that would break atomicity.</p>
</div>
<div class="section" id="s-transactions">
<span id="transactions"></span><h3>Transactions<a class="headerlink" href="#transactions" title="永久链接至标题">¶</a></h3>
<p>A transaction is an atomic set of database queries. Even if your program
crashes, the database guarantees that either all the changes will be applied,
or none of them.</p>
<p>Django doesn't provide an API to start a transaction. The expected way to
start a transaction is to disable autocommit with <a class="reference internal" href="#django.db.transaction.set_autocommit" title="django.db.transaction.set_autocommit"><code class="xref py py-func docutils literal notranslate"><span class="pre">set_autocommit()</span></code></a>.</p>
<p>Once you're in a transaction, you can choose either to apply the changes
you've performed until this point with <a class="reference internal" href="#django.db.transaction.commit" title="django.db.transaction.commit"><code class="xref py py-func docutils literal notranslate"><span class="pre">commit()</span></code></a>, or to cancel them with
<a class="reference internal" href="#django.db.transaction.rollback" title="django.db.transaction.rollback"><code class="xref py py-func docutils literal notranslate"><span class="pre">rollback()</span></code></a>. These functions are defined in <a class="reference internal" href="#module-django.db.transaction" title="django.db.transaction"><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.db.transaction</span></code></a>.</p>
<dl class="function">
<dt id="django.db.transaction.commit">
<code class="descname">commit</code>(<em>using=None</em>)<a class="headerlink" href="#django.db.transaction.commit" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="django.db.transaction.rollback">
<code class="descname">rollback</code>(<em>using=None</em>)<a class="headerlink" href="#django.db.transaction.rollback" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>These functions take a <code class="docutils literal notranslate"><span class="pre">using</span></code> argument which should be the name of a
database. If it isn't provided, Django uses the <code class="docutils literal notranslate"><span class="pre">&quot;default&quot;</span></code> database.</p>
<p>Django will refuse to commit or to rollback when an <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> block is
active, because that would break atomicity.</p>
</div>
<div class="section" id="s-topics-db-transactions-savepoints">
<span id="s-id3"></span><span id="topics-db-transactions-savepoints"></span><span id="id3"></span><h3>Savepoints<a class="headerlink" href="#topics-db-transactions-savepoints" title="永久链接至标题">¶</a></h3>
<p>A savepoint is a marker within a transaction that enables you to roll back
part of a transaction, rather than the full transaction. Savepoints are
available with the SQLite, PostgreSQL, Oracle, and MySQL (when using the InnoDB
storage engine) backends. Other backends provide the savepoint functions, but
they're empty operations -- they don't actually do anything.</p>
<p>Savepoints aren't especially useful if you are using autocommit, the default
behavior of Django. However, once you open a transaction with <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a>,
you build up a series of database operations awaiting a commit or rollback. If
you issue a rollback, the entire transaction is rolled back. Savepoints
provide the ability to perform a fine-grained rollback, rather than the full
rollback that would be performed by <code class="docutils literal notranslate"><span class="pre">transaction.rollback()</span></code>.</p>
<p>When the <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> decorator is nested, it creates a savepoint to allow
partial commit or rollback. You're strongly encouraged to use <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a>
rather than the functions described below, but they're still part of the
public API, and there's no plan to deprecate them.</p>
<p>Each of these functions takes a <code class="docutils literal notranslate"><span class="pre">using</span></code> argument which should be the name of
a database for which the behavior applies.  If no <code class="docutils literal notranslate"><span class="pre">using</span></code> argument is
provided then the <code class="docutils literal notranslate"><span class="pre">&quot;default&quot;</span></code> database is used.</p>
<p>Savepoints are controlled by three functions in <a class="reference internal" href="#module-django.db.transaction" title="django.db.transaction"><code class="xref py py-mod docutils literal notranslate"><span class="pre">django.db.transaction</span></code></a>:</p>
<dl class="function">
<dt id="django.db.transaction.savepoint">
<code class="descname">savepoint</code>(<em>using=None</em>)<a class="headerlink" href="#django.db.transaction.savepoint" title="永久链接至目标">¶</a></dt>
<dd><p>Creates a new savepoint. This marks a point in the transaction that is
known to be in a &quot;good&quot; state. Returns the savepoint ID (<code class="docutils literal notranslate"><span class="pre">sid</span></code>).</p>
</dd></dl>

<dl class="function">
<dt id="django.db.transaction.savepoint_commit">
<code class="descname">savepoint_commit</code>(<em>sid</em>, <em>using=None</em>)<a class="headerlink" href="#django.db.transaction.savepoint_commit" title="永久链接至目标">¶</a></dt>
<dd><p>Releases savepoint <code class="docutils literal notranslate"><span class="pre">sid</span></code>. The changes performed since the savepoint was
created become part of the transaction.</p>
</dd></dl>

<dl class="function">
<dt id="django.db.transaction.savepoint_rollback">
<code class="descname">savepoint_rollback</code>(<em>sid</em>, <em>using=None</em>)<a class="headerlink" href="#django.db.transaction.savepoint_rollback" title="永久链接至目标">¶</a></dt>
<dd><p>Rolls back the transaction to savepoint <code class="docutils literal notranslate"><span class="pre">sid</span></code>.</p>
</dd></dl>

<p>These functions do nothing if savepoints aren't supported or if the database
is in autocommit mode.</p>
<p>In addition, there's a utility function:</p>
<dl class="function">
<dt id="django.db.transaction.clean_savepoints">
<code class="descname">clean_savepoints</code>(<em>using=None</em>)<a class="headerlink" href="#django.db.transaction.clean_savepoints" title="永久链接至目标">¶</a></dt>
<dd><p>Resets the counter used to generate unique savepoint IDs.</p>
</dd></dl>

<p>The following example demonstrates the use of savepoints:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">django.db</span> <span class="kn">import</span> <span class="n">transaction</span>

<span class="c1"># open a transaction</span>
<span class="nd">@transaction</span><span class="o">.</span><span class="n">atomic</span>
<span class="k">def</span> <span class="nf">viewfunc</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>

    <span class="n">a</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
    <span class="c1"># transaction now contains a.save()</span>

    <span class="n">sid</span> <span class="o">=</span> <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint</span><span class="p">()</span>

    <span class="n">b</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>
    <span class="c1"># transaction now contains a.save() and b.save()</span>

    <span class="k">if</span> <span class="n">want_to_keep_b</span><span class="p">:</span>
        <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint_commit</span><span class="p">(</span><span class="n">sid</span><span class="p">)</span>
        <span class="c1"># open transaction still contains a.save() and b.save()</span>
    <span class="k">else</span><span class="p">:</span>
        <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint_rollback</span><span class="p">(</span><span class="n">sid</span><span class="p">)</span>
        <span class="c1"># open transaction now contains only a.save()</span>
</pre></div>
</div>
<p>Savepoints may be used to recover from a database error by performing a partial
rollback. If you're doing this inside an <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> block, the entire block
will still be rolled back, because it doesn't know you've handled the situation
at a lower level! To prevent this, you can control the rollback behavior with
the following functions.</p>
<dl class="function">
<dt id="django.db.transaction.get_rollback">
<code class="descname">get_rollback</code>(<em>using=None</em>)<a class="headerlink" href="#django.db.transaction.get_rollback" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<dl class="function">
<dt id="django.db.transaction.set_rollback">
<code class="descname">set_rollback</code>(<em>rollback</em>, <em>using=None</em>)<a class="headerlink" href="#django.db.transaction.set_rollback" title="永久链接至目标">¶</a></dt>
<dd></dd></dl>

<p>Setting the rollback flag to <code class="docutils literal notranslate"><span class="pre">True</span></code> forces a rollback when exiting the
innermost atomic block. This may be useful to trigger a rollback without
raising an exception.</p>
<p>Setting it to <code class="docutils literal notranslate"><span class="pre">False</span></code> prevents such a rollback. Before doing that, make sure
you've rolled back the transaction to a known-good savepoint within the current
atomic block! Otherwise you're breaking atomicity and data corruption may
occur.</p>
</div>
</div>
<div class="section" id="s-database-specific-notes">
<span id="database-specific-notes"></span><h2>Database-specific notes<a class="headerlink" href="#database-specific-notes" title="永久链接至标题">¶</a></h2>
<div class="section" id="s-savepoints-in-sqlite">
<span id="s-id4"></span><span id="savepoints-in-sqlite"></span><span id="id4"></span><h3>Savepoints in SQLite<a class="headerlink" href="#savepoints-in-sqlite" title="永久链接至标题">¶</a></h3>
<p>While SQLite supports savepoints, a flaw in the design of the <a class="reference external" href="https://docs.python.org/3/library/sqlite3.html#module-sqlite3" title="(在 Python v3.9)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a>
module makes them hardly usable.</p>
<p>When autocommit is enabled, savepoints don't make sense. When it's disabled,
<a class="reference external" href="https://docs.python.org/3/library/sqlite3.html#module-sqlite3" title="(在 Python v3.9)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">sqlite3</span></code></a> commits implicitly before savepoint statements. (In fact, it
commits before any statement other than <code class="docutils literal notranslate"><span class="pre">SELECT</span></code>, <code class="docutils literal notranslate"><span class="pre">INSERT</span></code>, <code class="docutils literal notranslate"><span class="pre">UPDATE</span></code>,
<code class="docutils literal notranslate"><span class="pre">DELETE</span></code> and <code class="docutils literal notranslate"><span class="pre">REPLACE</span></code>.) This bug has two consequences:</p>
<ul class="simple">
<li>The low level APIs for savepoints are only usable inside a transaction ie.
inside an <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> block.</li>
<li>It's impossible to use <a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> when autocommit is turned off.</li>
</ul>
</div>
<div class="section" id="s-transactions-in-mysql">
<span id="transactions-in-mysql"></span><h3>Transactions in MySQL<a class="headerlink" href="#transactions-in-mysql" title="永久链接至标题">¶</a></h3>
<p>If you're using MySQL, your tables may or may not support transactions; it
depends on your MySQL version and the table types you're using. (By
&quot;table types,&quot; we mean something like &quot;InnoDB&quot; or &quot;MyISAM&quot;.) MySQL transaction
peculiarities are outside the scope of this article, but the MySQL site has
<a class="reference external" href="https://dev.mysql.com/doc/refman/en/sql-transactional-statements.html">information on MySQL transactions</a>.</p>
<p>If your MySQL setup does <em>not</em> support transactions, then Django will always
function in autocommit mode: statements will be executed and committed as soon
as they're called. If your MySQL setup <em>does</em> support transactions, Django
will handle transactions as explained in this document.</p>
</div>
<div class="section" id="s-handling-exceptions-within-postgresql-transactions">
<span id="handling-exceptions-within-postgresql-transactions"></span><h3>Handling exceptions within PostgreSQL transactions<a class="headerlink" href="#handling-exceptions-within-postgresql-transactions" title="永久链接至标题">¶</a></h3>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">This section is relevant only if you're implementing your own transaction
management. This problem cannot occur in Django's default mode and
<a class="reference internal" href="#django.db.transaction.atomic" title="django.db.transaction.atomic"><code class="xref py py-func docutils literal notranslate"><span class="pre">atomic()</span></code></a> handles it automatically.</p>
</div>
<p>Inside a transaction, when a call to a PostgreSQL cursor raises an exception
(typically <code class="docutils literal notranslate"><span class="pre">IntegrityError</span></code>), all subsequent SQL in the same transaction
will fail with the error &quot;current transaction is aborted, queries ignored
until end of transaction block&quot;. While the basic use of <code class="docutils literal notranslate"><span class="pre">save()</span></code> is unlikely
to raise an exception in PostgreSQL, there are more advanced usage patterns
which might, such as saving objects with unique fields, saving using the
force_insert/force_update flag, or invoking custom SQL.</p>
<p>There are several ways to recover from this sort of error.</p>
<div class="section" id="s-transaction-rollback">
<span id="transaction-rollback"></span><h4>Transaction rollback<a class="headerlink" href="#transaction-rollback" title="永久链接至标题">¶</a></h4>
<p>The first option is to roll back the entire transaction. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">a</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># Succeeds, but may be undone by transaction rollback</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">b</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># Could throw exception</span>
<span class="k">except</span> <span class="n">IntegrityError</span><span class="p">:</span>
    <span class="n">transaction</span><span class="o">.</span><span class="n">rollback</span><span class="p">()</span>
<span class="n">c</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># Succeeds, but a.save() may have been undone</span>
</pre></div>
</div>
<p>Calling <code class="docutils literal notranslate"><span class="pre">transaction.rollback()</span></code> rolls back the entire transaction. Any
uncommitted database operations will be lost. In this example, the changes
made by <code class="docutils literal notranslate"><span class="pre">a.save()</span></code> would be lost, even though that operation raised no error
itself.</p>
</div>
<div class="section" id="s-savepoint-rollback">
<span id="savepoint-rollback"></span><h4>Savepoint rollback<a class="headerlink" href="#savepoint-rollback" title="永久链接至标题">¶</a></h4>
<p>You can use <a class="reference internal" href="#topics-db-transactions-savepoints"><span class="std std-ref">savepoints</span></a> to control
the extent of a rollback. Before performing a database operation that could
fail, you can set or update the savepoint; that way, if the operation fails,
you can roll back the single offending operation, rather than the entire
transaction. For example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">a</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># Succeeds, and never undone by savepoint rollback</span>
<span class="n">sid</span> <span class="o">=</span> <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint</span><span class="p">()</span>
<span class="k">try</span><span class="p">:</span>
    <span class="n">b</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># Could throw exception</span>
    <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint_commit</span><span class="p">(</span><span class="n">sid</span><span class="p">)</span>
<span class="k">except</span> <span class="n">IntegrityError</span><span class="p">:</span>
    <span class="n">transaction</span><span class="o">.</span><span class="n">savepoint_rollback</span><span class="p">(</span><span class="n">sid</span><span class="p">)</span>
<span class="n">c</span><span class="o">.</span><span class="n">save</span><span class="p">()</span> <span class="c1"># Succeeds, and a.save() is never undone</span>
</pre></div>
</div>
<p>In this example, <code class="docutils literal notranslate"><span class="pre">a.save()</span></code> will not be undone in the case where
<code class="docutils literal notranslate"><span class="pre">b.save()</span></code> raises an exception.</p>
</div>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Database transactions</a><ul>
<li><a class="reference internal" href="#managing-database-transactions">Managing database transactions</a><ul>
<li><a class="reference internal" href="#django-s-default-transaction-behavior">Django's default transaction behavior</a></li>
<li><a class="reference internal" href="#tying-transactions-to-http-requests">Tying transactions to HTTP requests</a></li>
<li><a class="reference internal" href="#controlling-transactions-explicitly">Controlling transactions explicitly</a></li>
</ul>
</li>
<li><a class="reference internal" href="#autocommit">Autocommit</a><ul>
<li><a class="reference internal" href="#why-django-uses-autocommit">Why Django uses autocommit</a></li>
<li><a class="reference internal" href="#deactivating-transaction-management">Deactivating transaction management</a></li>
</ul>
</li>
<li><a class="reference internal" href="#performing-actions-after-commit">Performing actions after commit</a><ul>
<li><a class="reference internal" href="#savepoints">Savepoints</a></li>
<li><a class="reference internal" href="#order-of-execution">Order of execution</a></li>
<li><a class="reference internal" href="#exception-handling">Exception handling</a></li>
<li><a class="reference internal" href="#timing-of-execution">Timing of execution</a></li>
<li><a class="reference internal" href="#use-in-tests">Use in tests</a></li>
<li><a class="reference internal" href="#why-no-rollback-hook">Why no rollback hook?</a></li>
</ul>
</li>
<li><a class="reference internal" href="#low-level-apis">Low-level APIs</a><ul>
<li><a class="reference internal" href="#managing-autocommit">Autocommit</a></li>
<li><a class="reference internal" href="#transactions">Transactions</a></li>
<li><a class="reference internal" href="#topics-db-transactions-savepoints">Savepoints</a></li>
</ul>
</li>
<li><a class="reference internal" href="#database-specific-notes">Database-specific notes</a><ul>
<li><a class="reference internal" href="#savepoints-in-sqlite">Savepoints in SQLite</a></li>
<li><a class="reference internal" href="#transactions-in-mysql">Transactions in MySQL</a></li>
<li><a class="reference internal" href="#handling-exceptions-within-postgresql-transactions">Handling exceptions within PostgreSQL transactions</a><ul>
<li><a class="reference internal" href="#transaction-rollback">Transaction rollback</a></li>
<li><a class="reference internal" href="#savepoint-rollback">Savepoint rollback</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="sql.html"
                        title="上一章">Performing raw SQL queries</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="multi-db.html"
                        title="下一章">Multiple databases</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../../_sources/topics/db/transactions.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">7月 23, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="sql.html" title="Performing raw SQL queries">previous</a>
     |
    <a href="../index.html" title="Using Django" accesskey="U">up</a>
   |
    <a href="multi-db.html" title="Multiple databases">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>